package com.huarun.module.approval.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.DateUtils;
import com.huarun.common.util.HttpUtil;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.SpringContextUtils;
import com.huarun.common.util.StringUtils;
import com.huarun.common.util.TokenUtil;
import com.huarun.module.airconditioning.bean.UseTime;
import com.huarun.module.applyrecord.bean.ApplyRecord;
import com.huarun.module.applyrecord.service.IApplyRecordService;
import com.huarun.module.approval.bean.Approval;
import com.huarun.module.approval.bean.CargoRelease;
import com.huarun.module.approval.bean.CargoReleaseDetail;
import com.huarun.module.approval.service.IApprovalService;
import com.huarun.module.cargorelease.bean.CargoReleaseApply;
import com.huarun.module.cargorelease.bean.Goods;
import com.huarun.module.cargorelease.service.ICargoReleaseApplyService;
import com.huarun.module.cargorelease.service.IGoodsService;
import com.huarun.module.repair.bean.AddResult;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.service.IUserService;

import io.swagger.annotations.ApiOperation;

/***
 * 
 * @author dzm
 * @创建时间 2018-10-29 16:13
 * @Description 审批
 */
@Controller
@RequestMapping("/wx/approval")
public class ApprovalController extends BaseController {

	@Resource
	private IApprovalService approvalService;
	@Resource
	private ICargoReleaseApplyService cargoReleaseApplyService;
	@Resource
	private IGoodsService goodsService;

	@Resource
	private IUserService userService;
	
	@Resource
	private IApplyRecordService applyRecordService;
//	private RedisUtils redis = null;
	
	@ApiOperation(value = "审批申请", notes = "审批申请")
	@RequestMapping(value = "/saveApproval", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<Object> saveApproval(Approval approval, HttpServletRequest req) {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		try {
			int count = approvalService.save(approval);
			log.error("更新{}条审批数据！", count);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("申请审批加时异常！");
			e.printStackTrace();
		}
		return rm;
	}

	@ApiOperation(value = "查询审批申请详情", notes = "审批申请详情")
	@RequestMapping(value = "/getApprovalDetail", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<CargoReleaseDetail> getApprovalDetail(@RequestParam Integer id) {
		ResponseMessage<CargoReleaseDetail> rm = new ResponseMessage<CargoReleaseDetail>();
		try {
			CargoReleaseApply cargoReleaseApply = cargoReleaseApplyService.getById(id);
			CargoRelease cargoRelease= new CargoRelease();
			cargoRelease.setStartTime(DateUtils.formatTimestamp.format(cargoReleaseApply.getStartTime()));
			cargoRelease.setEndTime(DateUtils.formatTimestamp.format(cargoReleaseApply.getEndTime()));
			cargoRelease.setCreateDate(cargoReleaseApply.getCreateDate());
			cargoRelease.setApplicant(cargoReleaseApply.getApplicant());
			cargoRelease.setApplyCompany(cargoReleaseApply.getApplyCompany());
			cargoRelease.setApprover(cargoReleaseApply.getApprover());
			cargoRelease.setCarrier(cargoReleaseApply.getCarrier());
			cargoRelease.setCarrierPhone(cargoReleaseApply.getCarrierPhone());
			cargoRelease.setId(cargoReleaseApply.getId());
			cargoRelease.setPhone(cargoReleaseApply.getPhone());
			cargoRelease.setRefusal(cargoReleaseApply.getRefusal());
			cargoRelease.setStatusCode(cargoReleaseApply.getStatusCode());
			cargoRelease.setStatus(cargoReleaseApply.getStatus());
			cargoRelease.setSynopsis(cargoReleaseApply.getSynopsis());
			List<Goods> goods = goodsService.findList(id);
			CargoReleaseDetail cargoReleaseDetail=new CargoReleaseDetail();
			cargoReleaseDetail.setCargoReleaseApply(cargoRelease);
			cargoReleaseDetail.setGoods(goods);
			rm.setData(cargoReleaseDetail);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("查询审批申请详情异常！");
			e.printStackTrace();
		}
		return rm;
	}
	
	@ApiOperation(value = "查询审批列表", notes = "查询审批列表")
	@RequestMapping(value = "/getPendingList", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<List<CargoReleaseApply>> getPendingList(HttpServletRequest req,@RequestParam String statusCode) {
		ResponseMessage<List<CargoReleaseApply>> rm = new ResponseMessage<>();
		try {
			Map<String, Object> params =new HashMap<>();
			String synId=req.getHeader("synId");
			String synMainId=req.getHeader("synMainId");
			String projectId=req.getHeader("projectId");
			if(null==statusCode) {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "未传入审核状态");
				return rm;
			}
			List<String> idList=StringUtils.stringConvertList(statusCode);
			params.put("statusCodes",idList);
			//如果子管理ID和主管理ID是同一个的话，那么这个人就是主管理员了，则可以查询这个项目下这个租户的所有记录（包括子管理）
			//如果ID不同，那么只能查看到这个项目下自己提交的记录了
			params.put(projectId, projectId);
			if(null==synId || null==synMainId) {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "管理员信息有误，请刷新操作");
				return rm;
			}
			//4/11日 刘芳取消掉此需求，不管子管理还是管理，都要能看到这个租户下的所有待审核信息
//			if(synId.equals(synMainId)) {
				params.put("synMainId", synMainId);
//			}else {
//				params.put("synId", synId);
//			}
			params.put("projectId", projectId);
			List<CargoReleaseApply> list = cargoReleaseApplyService.findList(params);
			rm.setData(list);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("查询审批列表异常！");
			e.printStackTrace();
		}
		return rm;
	}

	
	@ApiOperation(value = "批准", notes = "批准")
	@RequestMapping(value = "/approval", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Object> approval(@RequestParam Integer id,
			HttpServletRequest req) {
//		// 1.获取事务控制管理器
//		DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) SpringContextUtils
//				.getBeanById("transactionManager");
//		// 2.获取事务定义
//		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//		// 3.设置事务隔离级别，开启新事务
//		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
//		// 4.获得事务状态
//		TransactionStatus status = transactionManager.getTransaction(def);
		int resultCount=0;
		ResponseMessage<Object> rm = new ResponseMessage<Object>();	
		String projectId=req.getHeader("projectId");
		String applyRowGuid=req.getHeader("RowGuid");
 		Map<String, Object> params=new HashMap<String, Object>();
		CargoReleaseApply cargoReleaseApply = cargoReleaseApplyService.getById(id);
		if(!cargoReleaseApply.getStatus().equals("待审批")){
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "此申请已审批完成");
			return rm;
		}
		
		List<Goods> goods = goodsService.findList(id);
		StringBuffer description=new StringBuffer();
		if (goods!=null&&goods.size()>0) {
			for (Goods goods2 : goods) {
				description.append(goods2.getName());
				description.append("*");
				//数量由原来的1.0修改为1，需求提出人刘芳，修改人eva 2019-3-20
				description.append(goods2.getAmount().intValue());
				description.append(";");
			}
		}
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		long time = System.currentTimeMillis();
		try {
    		String url=Constant.WORK_INSERT;	
    	    List<UseTime> useTimeInfoList =new ArrayList<>();
    	    UseTime usetime=new UseTime();
    	    usetime.setStartDate(DateUtils.SHORT_DATE_FORMAT.format(cargoReleaseApply.getStartTime()));
    	    usetime.setEndDate(DateUtils.SHORT_DATE_FORMAT.format(cargoReleaseApply.getEndTime()));
    	    usetime.setStartTime(DateUtils.HM_FORMAT.format(cargoReleaseApply.getStartTime()));
    	    usetime.setEndTime(DateUtils.HM_FORMAT.format(cargoReleaseApply.getEndTime()));  
    	    useTimeInfoList.add(usetime);
    		params.put("ApplyRowGuid", applyRowGuid);
    		params.put("ApplyTime", cargoReleaseApply.getCreateDate());
    		params.put("ProjectGuid", projectId);
    		params.put("ApplyType", Constant.RG_APPLY_TYPE_APPROVAL);//戎光货物放行选2
    		params.put("ApplyName", cargoReleaseApply.getApplicant());
    		params.put("TelPhone", cargoReleaseApply.getPhone());
    		params.put("CarryingPerson", cargoReleaseApply.getCarrier());
    		params.put("CarryingPersonTel", cargoReleaseApply.getCarrierPhone());
    		params.put("Description",description.toString());
    		params.put("UseTimeInfo",JSON.toJSONString(useTimeInfoList));
//    		String token=TokenUtil.createToken(url,time, params);
    		Map<String,Object> map=TokenUtil.createToken(url, time, params);
			String token = map.get("token").toString();
    		url=url+"?token="+token;
    		params.put("appkey",Constant.MANAGE_APPKEY);
    		params.put("time",time);
    		params.put("UseTimeInfo",useTimeInfoList);
    		String json = JSON.toJSONString(params);
//			String resultStr=HttpUtil.postGeneralUrl(Constant.BASE_URL+url, "application/json,text/json", json, "UTF-8");
    		String resultStr=HttpUtil.postGeneralUrl(Constant.BASE_URL+url, "application/json,text/json", map.get("parms").toString(), "UTF-8");
		    JSONObject imisObj = JSONObject.parseObject(resultStr);
            String errorCode=imisObj.getString("ErrorCode");
    		if (Constant.RG_SUCCESS_CODE.equals(errorCode)) {
    			JSONObject data=imisObj.getJSONObject("Data"); 
        		AddResult addResult=JSONObject.toJavaObject(data, AddResult.class);
        		cargoReleaseApply.setOperateNo(addResult.getValue());
        		cargoReleaseApply.setStatus("已审批");
        		cargoReleaseApply.setStatusCode(2);
        		String openId=req.getHeader("openId");     
        		Map<String, Object> param=new HashMap<String, Object>();
        		param.put("openId", openId);
        		User user = userService.getUserByParams(param);
        		cargoReleaseApply.setApprover(user.getUserName());
//        		cargoReleaseApply.setApprover("康力方");
        		resultCount=cargoReleaseApplyService.update(cargoReleaseApply);
				ApplyRecord entity=applyRecordService.getByOperateNo(String.valueOf(cargoReleaseApply.getId()));
				entity.setOperateNo(addResult.getValue());
				resultCount=applyRecordService.update(entity);
    			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
    		}else {
    			JSONObject data=imisObj.getJSONObject("Data"); 
    			String message=data.getString("FailReason");
    			//rm.setCodeAndMsg(Integer.parseInt(errorCode),imisObj.getString("ErrorMessage")+message);
    			rm.setCodeAndMsg(Integer.parseInt(errorCode),message);
			}	
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("批准申请异常！");
			resultCount=-1;
			e.printStackTrace();
		}
//		finally {
//			if (resultCount<=0) {
//				//如果获取明细插入失败，那么这条申请也不会成功
//				transactionManager.rollback(status);
//			} else {
//				transactionManager.commit(status);
//			}
//		}
	
		return rm;
	}
	@ApiOperation(value = "拒绝", notes = "拒绝")
	@RequestMapping(value = "/refuse", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Object> refuse(@RequestParam Integer id,@RequestParam String refusal,
			HttpServletRequest req) {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();	
		CargoReleaseApply cargoReleaseApply = cargoReleaseApplyService.getById(id);
		if(!"待审批".equals(cargoReleaseApply.getStatus())){
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "此申请已审批完成");
			return rm;
		}
		
		List<Goods> goods = goodsService.findList(id);
		StringBuffer description=new StringBuffer();
		for (Goods goods2 : goods) {
			description.append(goods2.getName());
			description.append("*");
			description.append(goods2.getAmount().intValue());
			description.append(";");
		}
		try {
        cargoReleaseApply.setStatus("审批已拒绝");
        cargoReleaseApply.setStatusCode(1);
        cargoReleaseApply.setRefusal(refusal);
		String openId=req.getHeader("openId");    
		Map<String, Object> param=new HashMap<String, Object>();
		param.put("openId", openId);
		User user = userService.getUserByParams(param);
		cargoReleaseApply.setApprover(user.getUserName());
//		cargoReleaseApply.setApprover("康力方");
        cargoReleaseApplyService.update(cargoReleaseApply);
    	rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);	
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("拒绝申请异常！");
			e.printStackTrace();
		}
		return rm;
	}
	
	@ApiOperation(value = "待审批数量", notes = "待审批数量")
	@RequestMapping(value = "/pendingcount", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Object> pendingcount(HttpServletRequest req) {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		try {
			Map<String, Object> params =new HashMap<String, Object>();
			List<String> idList=new ArrayList<>(1);
			idList.add("0");
			params.put("statusCodes",idList);
			String synId=req.getHeader("synId");
			String synMainId=req.getHeader("synMainId");
			String projectId=req.getHeader("projectId");
			//如果子管理ID和主管理ID是同一个的话，那么这个人就是主管理员了，则可以查询这个项目下这个租户的所有记录（包括子管理）
			//如果ID不同，那么只能查看到这个项目下自己提交的记录了
			params.put(projectId, projectId);
			if(null==synId || null==synMainId) {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "管理员信息有误，请刷新操作");
				return rm;
			}
			//4/11日 刘芳取消掉此需求，不管子管理还是管理，都要能看到这个租户下的所有待审核信息
//			if(synId.equals(synMainId)) {
				params.put("synMainId", synMainId);
//			}else {
//				params.put("synId", synId);
//			}
			params.put("projectId", projectId);
			List<CargoReleaseApply> list = cargoReleaseApplyService.findList(params);
			if (list!=null && list.size()>0) {
				rm.setData(list.size());
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			}else {
				rm.setData(0);
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			}
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("查询审批申请详情异常！");
			e.printStackTrace();
		}
		return rm;
	}
}
